package com.wiringweb.resolution;

import com.wiringweb.exceptions.WiringWebException;
import com.wiringweb.servlet.WiringRequestProcessor;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Dmitry
 */
public class ErrorResolution implements Resolution {
    int errorCode = 500;
    String message;

    public ErrorResolution(int errorCode, String message) {
        this.errorCode = errorCode;
        this.message = message;
    }

    public ErrorResolution(String message) {
        this.message = message;
    }
    
    public ErrorResolution(Throwable exception) {
        while(true){
            if(exception.getCause()==null){
                break;
            }
            exception=exception.getCause();
        }
        this.message = String.format("%s:%s", exception.getClass().getName(), exception.getMessage());
    }

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response, WiringRequestProcessor requestProcessor, ServletConfig servletConfig) {
        try {
            response.setStatus(errorCode);
            response.sendError(errorCode, message);
        } catch (IOException ex) {
            throw new WiringWebException("Cannot send error. Message:" + message);
        }
    }
}
